package com.gomtel.smartdevice.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * 图片操作
 */
@SuppressWarnings("ALL")
public class BitmapUtil {
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            int halfHeight = height / 2;
            int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    // 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响
    public static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight) {
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (!Objects.equals(src, dst)) { // 如果没有缩放，那么不回收
            src.recycle(); // 释放Bitmap的native像素数组
        }
        return dst;
    }

    // 从Resources中加载图片
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options); // 读取图片长款
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 计算inSampleSize
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeResource(res, resId, options); // 载入一个稍大的缩略图
        return createScaleBitmap(src, reqWidth, reqHeight); // 进一步得到目标大小的缩略图
    }

    // 从sd卡上加载图片
    public static Bitmap decodeSampledBitmapFromFd(String pathName, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(pathName, options);
        return createScaleBitmap(src, reqWidth, reqHeight);
    }

    //获取图片的宽高
    public static int[] getImageWidthHeight(Resources resources, int id) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        /*
         * 最关键在此，把options.inJustDecodeBounds = true;
         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, id, options); // 此时返回的bitmap为null
        /*
         *options.outHeight为原始图片的高
         */
        return new int[]{options.outWidth, options.outHeight};
    }

    //Drawable转Bitmap
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 保存Bitmap到手机本地(透明色会填充成黑色,暂时无法解决)
     *
     * @param pathName 需要保存的文件父路径
     * @param bitmap   图像
     * @return 路径
     */
    public static String saveBitmapToLocalFile(String pathName, Bitmap bitmap) {
        File orcPath = new File(pathName);
        if (!orcPath.exists() || !orcPath.isDirectory()) {
            throw new IllegalArgumentException("pathName must be a directory");
        }
        String fileName = System.currentTimeMillis() + ".png";
        //获取缓存目录
        String filePath = pathName + File.separator + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    //将Bitmap做镜像处理
    public static Bitmap getMirror180Degrees(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        matrix.preRotate(180);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        resizedBitmap.setHasAlpha(true);
        bitmap.recycle();
        return resizedBitmap;
    }

    //将Bitmap转换成圆角图形
    public Bitmap getRoundCornerImage(Bitmap bitmap, int roundPixels) {
        /*创建一个和原始图片一样大小位图*/
        Bitmap roundCornerImage = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        /*创建带有位图roundCornerImage的画布*/
        Canvas canvas = new Canvas(roundCornerImage);
        /*创建画笔  */
        Paint paint = new Paint();
        /*创建一个和原始图片一样大小的矩形*/
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectF = new RectF(rect);
        /*去锯齿*/
        paint.setAntiAlias(true);
        /*画一个和原始图片一样大小的圆角矩形*/
        canvas.drawRoundRect(rectF, roundPixels, roundPixels, paint);
        /*设置相交模式  */
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        /*把图片画到矩形去  */
        canvas.drawBitmap(bitmap, rect, rectF, paint);
        /*引时圆角区域为透明，给其填充透明色  */
        paint.setColor(Color.TRANSPARENT);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
        canvas.drawRect(rectF, paint);
        //回收
        bitmap.recycle();
        return roundCornerImage;
    }

    /**
     * 根据原图和变长绘制圆形图片
     *
     * @param source 原图片
     * @param radius 角度
     * @return 图像
     */
    public static Bitmap createCircleImage(Bitmap source, int radius) {
        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
        /*
         * 产生一个同样大小的画布
         */
        Canvas canvas = new Canvas(target);
        /*
         * 首先绘制圆形
         */
        canvas.drawCircle(radius / 2, radius / 2, radius / 2, paint);
        /*
         * 使用SRC_IN，参考上面的说明
         */
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        /*
         * 绘制图片
         */
        canvas.drawBitmap(source, 0, 0, paint);
        source.recycle();
        return target;
    }

    //把黑色转换成透明
    public static Bitmap getImageBlackToTransparent(Bitmap mBitmap) {
        Bitmap createBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        int mWidth = mBitmap.getWidth();
        int mHeight = mBitmap.getHeight();
        for (int i = 0; i < mHeight; i++) {
            for (int j = 0; j < mWidth; j++) {
                int color = mBitmap.getPixel(j, i);
                int g = Color.green(color);
                int r = Color.red(color);
                int b = Color.blue(color);
                int a = Color.alpha(color);
                if (g <= 5 && r <= 5 && b <= 5) {
                    a = 0;
                }
                color = Color.argb(a, r, g, b);
                createBitmap.setPixel(j, i, color);
            }
        }
        mBitmap.recycle();
        return createBitmap;
    }

    //把白色转换成透明
    public static Bitmap getImageWhiteToTransparent(Bitmap mBitmap) {
        Bitmap createBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        int mWidth = mBitmap.getWidth();
        int mHeight = mBitmap.getHeight();
        for (int i = 0; i < mHeight; i++) {
            for (int j = 0; j < mWidth; j++) {
                int color = mBitmap.getPixel(j, i);
                int g = Color.green(color);
                int r = Color.red(color);
                int b = Color.blue(color);
                int a = Color.alpha(color);
                if (g >= 250 && r >= 250 && b >= 250) {
                    a = 0;
                }
                color = Color.argb(a, r, g, b);
                createBitmap.setPixel(j, i, color);
            }
        }
        mBitmap.recycle();
        return createBitmap;
    }

    //把透明转换成白色
    public static Bitmap getImageTransparentToWhite(Bitmap mBitmap) {
        if (mBitmap != null) {
            int mWidth = mBitmap.getWidth();
            int mHeight = mBitmap.getHeight();
            for (int i = 0; i < mHeight; i++) {
                for (int j = 0; j < mWidth; j++) {
                    int color = mBitmap.getPixel(j, i);
                    int g = Color.green(color);
                    int r = Color.red(color);
                    int b = Color.blue(color);
                    int a = Color.alpha(color);
                    if (a == 0) {
                        a = 255;
                        g = 255;
                        r = 255;
                        b = 255;
                    }
                    color = Color.argb(a, b, g, r);
                    mBitmap.setPixel(j, i, color);
                }
            }
        }
        return mBitmap;
    }
}